from PyQt6 import QtWidgets
from PyQt6.QtWidgets import QDialog, QFileDialog, QMessageBox
import sys
import os
from PyQt6.QtCore import QProcess
import subprocess  # 用于执行外部 Python 脚本
import webbrowser  # 用于打开浏览器
from ResourceAnalysis.resouce_statistics import Ui_Dialog  # 导入生成的UI类相关的配置


class MonitoringDialog(QDialog):
    def __init__(self):
        super(MonitoringDialog, self).__init__()
        self.ui = Ui_Dialog()  # 创建 UI 实例
        self.ui.setupUi(self)  # 设置 UI

        # 设置按钮的信号连接
        self.ui.pushButton_2.clicked.connect(lambda: self.openFileDialog(1))
        self.ui.pushButton_5.clicked.connect(lambda: self.openFileDialog(2))
        self.ui.pushButton_4.clicked.connect(lambda: self.openFileDialog(3))
        self.ui.pushButton.clicked.connect(lambda: self.openFileDialog(4))
        self.ui.pushButton_3.clicked.connect(lambda: self.openFileDialog(5))

    def openFileDialog(self, type):
        """打开文件选择对话框"""
        file_name, _ = QFileDialog.getOpenFileName(self, "Select TXT File", "", "Text Files (*.txt)")
        if file_name:
            try:
                # 更新 textEdit 显示过程信息
                self.ui.textEdit.append("File selected: " + file_name)
                self.ui.textEdit.append("Now type is " + str(type))

                # 调用 transfor_html_full.py 并传递文件路径和生成文件路径
                if type == 1:
                    # 创建输出路径的目录
                    output_dir = os.path.dirname("/tmp/full/full.html")
                    os.makedirs(output_dir, exist_ok=True)  # 如果目录不存在则创建

                    # 清空输出目录中的旧文件
                    for file in os.listdir(output_dir):
                        file_path = os.path.join(output_dir, file)
                        if os.path.isfile(file_path):
                            os.remove(file_path)

                    self.call_transform_script("ResourceAnalysis/transfor_html_full.py", file_name, "/tmp/full/full.html")
                elif type == 2:
                    # 创建输出路径的目录
                    output_dir = os.path.dirname("/tmp/part/part.html")
                    os.makedirs(output_dir, exist_ok=True)  # 如果目录不存在则创建

                    # 清空输出目录中的旧文件
                    for file in os.listdir(output_dir):
                        file_path = os.path.join(output_dir, file)
                        if os.path.isfile(file_path):
                            os.remove(file_path)

                    self.call_transform_script("ResourceAnalysis/transfor_html_part.py", file_name, "/tmp/part/part.html")
                elif type == 3:
                    # self.ui.textEdit.append(f"Will exec call_top_script...")
                    self.call_top_script(file_name, "ResourceAnalysis/top.py")
                elif type == 4:
                    # self.ui.textEdit.append(f"Will exec call_top_script...")
                    self.call_top_script(file_name, "ResourceAnalysis/proc.py")
                elif type == 5:
                    # self.ui.textEdit.append(f"Will exec call_top_script...")
                    self.call_top_script(file_name, "ResourceAnalysis/average.py")

            except Exception as e:
                # 如果发生问题，显示错误消息
                QMessageBox.critical(self, "Error", f"An error occurred: {e}")
                self.ui.textEdit.append(f"Error: {e}")

    def call_transform_script(self, py_gen_html_path, txt_file_path, output_html_path):
        """调用 transfor_html_full.py 脚本"""
        try:
            # 在调用脚本前更新文本框
            self.ui.textEdit.append(f"Running transformation script on {txt_file_path}...")

            # 调用 transform_html_full.py 脚本，传递两个参数：txt 文件路径和输出的 HTML 文件路径
            result = subprocess.run(
                ['python3', py_gen_html_path, txt_file_path, output_html_path],
                check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
            )

            # 打印 Python 脚本的标准输出到 textEdit
            self.ui.textEdit.append("Transformation script executed successfully.")
            self.ui.textEdit.append(result.stdout)

            # 执行完成后，自动在浏览器中打开生成的 HTML 文件
            webbrowser.open(f'file://{output_html_path}')

            # 更新 textEdit，显示文件已用浏览器打开
            self.ui.textEdit.append("The HTML file has been opened in the browser. Please check.")

        except subprocess.CalledProcessError as e:
            # 如果脚本执行失败，显示错误消息
            QMessageBox.critical(self, "Error", f"Failed to run the transformation script: {e}")
            self.ui.textEdit.append(f"Failed to run the script: {e.stderr}")
        except Exception as e:
            # 捕获其他异常
            QMessageBox.critical(self, "Error", f"An error occurred while calling the transformation script: {e}")
            self.ui.textEdit.append(f"Error: {e}")

    def call_top_script(self, txt_file_path, script_file_path):
        """调用 top.py 脚本"""
        try:
            self.ui.textEdit.append(f"Running top.py script on {txt_file_path}...")

            process = QProcess(self)
            process.setProgram("python3")
            process.setArguments([script_file_path, txt_file_path])

            # 连接信号槽，获取输出
            process.readyReadStandardOutput.connect(self.handle_stdout)
            process.readyReadStandardError.connect(self.handle_stderr)

            process.start()
            if not process.waitForStarted():
                raise Exception(f"Failed to start process: {process.errorString()}")

            process.waitForFinished()

        except Exception as e:
            QMessageBox.critical(self, "Error", f"An error occurred while calling the top script: {e}")
            self.ui.textEdit.append(f"Error: {e}")

    def handle_stdout(self):
        """处理标准输出"""
        process = self.sender()
        output = process.readAllStandardOutput().data().decode()
        self.ui.textEdit.append(output)

    def handle_stderr(self):
        """处理标准错误输出"""
        process = self.sender()
        error_output = process.readAllStandardError().data().decode()
        self.ui.textEdit.append(f"Error: {error_output}")

